package com.alibaba.algo.components.yapi;

import java.lang.reflect.Method;

import javax.annotation.Resource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.algo.components.yapi.annotations.Api;
import com.alibaba.algo.components.yapi.service.YapiService;

@Component
public class YapiListenerProcessor implements BeanPostProcessor {
	@Autowired
	private YapiService yapiService;
	@Resource
	private Environment env;

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		String autoRegister = env.getProperty("yapi.auto-register");
		if (StringUtils.isEmpty(autoRegister) || !Boolean.valueOf(autoRegister)) {
			return bean;
		}
		Class<?> clazz = bean.getClass();
		Api apiAnnotatio = clazz.getAnnotation(Api.class);
		if (apiAnnotatio == null) {
			return bean;
		}
		// 校验接口分类是否存在
		Integer catId = yapiService.getCatId(apiAnnotatio);
		if (catId == null) {
			return bean;
		}
		// 获取ApiOperation注解
		Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
		if (methods == null || methods.length == 0) {
			return bean;
		}
		yapiService.registerYapi(catId, clazz, methods);
		return bean;
	}
}
